Guided Practice 12.1 - Solution

The question was:

Consider the following set of class definitions and object definitions:

(define Class1%
  (class* object% ()
    (init-field a)
    (field [c (+ a 5)])

    (super-new)
    
    ;; Number -> Number
    (define/public (m1 x)
      (if (>= x 106) x
        (send this m2 (- x a))))
    
    ;; Number -> Number
    (define/public (m2 x) (+ x c))

    ))

(define Class2%
  (class* Class1% ()
    (inherit-field a c)
    (init-field b)

    (super-new [a (+ b 1)])

    ;; Number -> Number
    (define/override (m1 x) (- x c))
    
    ))

(define Class3%
  (class* Class1% ()
    (inherit-field a c)
    
    (super-new)

    ;; Number -> Number
    (define/override (m2 x) (send this m1 (+ x c)))

    ))

(define Class4%
  (class* Class2% ()
    (inherit-field a c)
    (super-new)
    (define/override (m2 x) (+ x c)) ))

(define obj1 (new Class1% [a 10]))
(define obj2 (new Class2% [b 20]))
(define obj3 (new Class3% [a 30]))
(define obj4 (new Class4% [b 40]))

Without running the program, determine the value of each pair of method calls below.

1. (send obj1 m1 100) and (send obj1 m2 100)

Answer:
a)	105 and 115
b)	105 and 130
c)	110 and 115

Correct Answer:  a) 105 and 115

Feedback: (new Class1% [a 10]) builds an object of class Class1% with
fields a = 10 and c = 15.  this refers to obj1. Then  

(send obj1 m1 100) 
= (send this m2 (- 100 10))
= (send obj1 m2 90)
= (+ 90 15)
= 105

(send obj1 m2 100)
= (+ 100 15)
= 115

2. (send obj2 m1 100) and (send obj2 m2 100)

Answer:
a)	54 and 74
b)	74 and 126
c)	126 and 146

Correct Answer: b) 74 and 126

Feedback: (new Class2% [b 20]) builds an object of class Class2% with
b = 20, a = 21 (bound in the invocation of super-new), and c =
26. this refers to obj2.  obj2's m1 method is the one defined in
Class2%, but its m2 method is inherited from its parent Class1%.  So

(send obj2 m1 100)
= (- x c)
= (- 100 26)
= 74

(send obj2 m2 100)
= (+ x c)
= (+ 100 26)
= 126

3. (send obj3 m1 100) and (send obj3 m2 100)


Answer
a)	110 and 126
b)	105 and 130
c)	110 and 130

Correct Answer: c) 110 and 130

Feedback: (new Class3% [a 30]) builds an object of class Class3%, with
a = 30 and c = 35.  Class3%'s m1 method is that of Class1%, but its m2
method is the one defined in Class3%.  So 

(send obj3 m1 100)
= (send this m2 (- 100 30))
= (send obj3 m2 70)
= (send this m1 (+ 70 35))
= (send obj3 m1 110)
= 110  

4. (send obj4 m1 100) and (send obj4 m2 100)

Answer:
a)	105 and 146
b)	54 and 146
c)	115 and 146

Correct Answer:  b) 54 and 146.

Feedback: (new Class4% [b 40]) builds an object of class Class4%, with
b = 40, a = 41 [initialized in Class2%], and c = 46 [initialized in
Class1%].   Class4%'s m1 method is inherited from Class2%, and its m2
method is the one defined in Class4%.  So 

(send obj4 m1 100) 
= (- 100 46)
= 54

(send obj4 m2 100)
= (+ 100 46)
= 146

Last modified: Wed Nov 19 15:38:35 Eastern Standard Time 2014